<?php
/**
 * Created by PhpStorm.
 * User: ybjaa
 * Date: 2017/6/19
 * Time: 23:47
 */

namespace App\Http\Controllers;


use database\model\base;
use database\model\GetModels;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class DataBaseController extends Controller
{


    protected function CreateTables($tables,$drop=false)
    {
        foreach($tables as $t)
        {
            if($drop==true){
                Schema::dropIfExists($t->table);
            }

            if(!Schema::hasTable($t->table))
            {
                Schema::create($t->table, function (Blueprint $table)use ($t) {
                    $t->CreateFileds($table);
                });
            }

        }

    }



    public function DataBaseAllInitialize()
    {
        $parameter=$this->getParameters();
        $drop=false;
        if($parameter)
        {
            $drop=(bool)$parameter->drop;
        }


        $tables= array_merge(GetModels::GetBaseLogModels(),
            GetModels::GetBaseModels(),
            GetModels::GetBaseBusinessModels()
        );

        $this->CreateTables($tables,$drop);

        return "true";

    }


    public function DataBaseLogInitialize()
    {
        $parameter=$this->getParameters();
        $drop=false;
        if($parameter)
        {
            $drop=(bool)$parameter->drop;
        }

        $tables=GetModels::GetBaseLogModels();

        $this->CreateTables($tables,$drop);

        return "true";
    }


    public function DataBaseBaseInitialize()
    {
        $parameter=$this->getParameters();
        $drop=false;
        if($parameter)
        {
            $drop=(bool)$parameter->drop;
        }

        $tables=GetModels::GetBaseModels();

        $this->CreateTables($tables,$drop);

        return "true";
    }


    public function DataBaseBisInitialize()
    {
        $parameter=$this->getParameters();
        $drop=false;
        if($parameter)
        {
            $drop=(bool)$parameter->drop;
        }

        $tables=GetModels::GetBaseBusinessModels();


        $this->CreateTables($tables,$drop);

        return "true";

    }

    public function DataBaseCreateViews()
    {
        DB::statement("CREATE OR REPLACE VIEW view_biz_ybj_jssb_file AS select `bis_ybj_jssb_files`.`ID` AS `ID`,`files`.`ID` AS `FileID`,`files`.`userID` AS `userID`,`users`.`UserName` AS `userName`,`files`.`size` AS `size`,`files`.`suffix` AS `suffix`,`files`.`fileUrlPath` AS `fileUrlPath`,`bis_ybj_jssb_files`.`created_at` AS `created_at` from ((`bis_ybj_jssb_files` left join `files` on((`bis_ybj_jssb_files`.`fileID` = `files`.`ID`))) left join `users` on((`files`.`userID` = `users`.`ID`))) order by `bis_ybj_jssb_files`.`created_at` desc");
    }

}